define(function(require, exports, module) {
    'use strict';

    var rk = require('rk');
    require('../../../common/xsyGrid/widget');
    require('./gridView/widget');
    require('./cardView/widget');

    $.widget('rk.xsySuRefer', $.rk.xsyBase, {
        options: {
            iconClass: ''
        },
        _create: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            //监听新建刷新
            me._listenOuterEvent('reloadRefer', function(event) {
                if (event.entity === opt.business) {
                    me._reload();
                }
            });
            me._beIniting();
        },
        _init: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

        },
        getTitle: function() {
            return this.options.title;
        },
        getAmount: function() {
            return this.options.amount;
        },
        _getCard: function() {
            var me = this;
            var elem = me.element;
            return me.body.find('>.xsy_su_refer_card');
        },
        _getGrid: function() {
            var me = this;
            var elem = me.element;
            return me.body.find('>.xsy_su_refer_grid');
        },
        _getReferHeaderNum: function() {
            var me = this;
            var elem = me.element;
            return elem.find('span.xsy_su_refer_num_num');
        },
        _getCurrentViewElem: function() {
            var me = this;
            return me.body.find('>[current="true"]');
        },
        _getCurrentViewtype: function() {
            var me = this;
            var current = me.body.find('>[current="true"]');
            if (current.hasClass('xsy_su_refer_card')) return 'card';
            if (current.hasClass('xsy_su_refer_grid')) return 'grid';
            return 'customized'
        },
        _render: function(config, result) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            if( elem.parents('.NARROW').size() > 0 ){//窄区域中，不显示grid视图
                config.children = _.remove(config.children, function(n) {
                                      return n.type !== 'grid';
                                    });
            }

            //如果是多业务类型，但是没有返回业务类型，干掉
            me._processMultiTypeEntity(result, config);

            if (typeof result == 'undefined') result = {};
            if (!opt.attributes) opt.attributes = {
                expandedFlg: 1,
                maxCardColCount: 4,
                maxCardRowCount: 6,
                maxGridColCount: 6,
                maxGridRowCount: 10,
                showMode: "card"
            };
            if (!opt.attributes.showMode) opt.attributes.showMode = 'card';
            config.opt = opt;
            config.data = result;
            opt.haveData = (result.self && result.self.dataCount && result.self.dataCount >= 0) ? true : false;
            config.amount = (result.self && result.self.dataCount) ? result.self.dataCount : 0;
            config.title = (result.self && result.self.name) ? result.self.name : '{{name}}';
            if (!$.isArray(config.buttons)) config.buttons = [];
            if (opt.userPermission && opt.userPermission != 'all' && opt.userPermission.c !== 1) {
                config.buttons = _.reject(config.buttons, function(val) {
                    return (val == 'create') || (val.act == 'create');
                });
            }
            if(opt.userPermission && opt.userPermission != 'all' && opt.userPermission.u !== 1){
                config.buttons = _.reject(config.buttons, function(val) {
                    return (val == 'edit') || (val.act == 'edit');
                });
            }
            if (result.self && $.isArray(result.self.entityTypes)) {
                config.entityTypes = result.self.entityTypes;
            } else {
                config.entityTypes = [];
            }
            if (typeof config.showEntityMenu == 'undefined') config.showEntityMenu = true;
            config.isFold = !(opt.attributes.expandedFlg == 1);

            me.currentServerData = result.self; //缓存


            if (typeof config.showMoreBtn == 'undefined') config.showMoreBtn = true;

            //没有数据不显示更多和展开区域
            if(me.currentServerData && me.currentServerData.entityData && me.currentServerData.entityData.length < 1){
                config.showMoreBtn = false;
                config.isFold = false;
            }

            if ($.isArray(config.children)) {
                for (var i = 0, len = config.children.length; i < len; i++) {
                    var cfg = config.children[i];
                    if (cfg.type == 'card') {
                        if (!cfg.menuItems) cfg.menuItems = [/*{
                            act: 'edit',
                            title: rk.i18n('CRM_CORE_EDIT')
                        }, */{
                            act: 'delete',
                            title: rk.i18n('CRM_CORE_DELETE')
                        },{
                            act : 'remove',
                            title : rk.i18n('CRM_CORE_REMOVE')
                        }, {
                            act: 'transfer',
                            title: rk.i18n('CRM_CORE_TRANSFER')
                        }];
                        config.cardConfig = cfg;
                        config.showCard = true
                    } else if (cfg.type == 'grid') {
                        config.gridConfig = cfg;
                        config.showGrid = true;
                    } else if (cfg.html) {
                        config.bodyConfig = cfg;
                    }
                }
            }
            if (config.bodyConfig) config.bodyHtml = config.bodyConfig.html;
            config.detailId = me._getDetailId();

            var relationTypes = {
                1: 'accountId',
                2: 'contactId',
                3: 'opportunityId',
                15: 'contractId',
                35: 'orderId',
                12: 'caseId'
            };
            config.relationType = relationTypes[opt.parentEntityId] ? relationTypes[opt.parentEntityId] : 'belongId';
            //console.log(config);
            var tpl = me.getTpl();
            var html = rk.templateText(tpl, config);
            elem.html(html);

            me.header = elem.find('div.xsy_su_refer_header');
            me.body = elem.find('div.xsy_su_refer_body');

            //初始化右上角菜单按钮
            me._initHeaderEvents(config);
            //初始化内容区域的小菜单
            me._initBodyEvents(config);
            //初始化内部监听
            me._initInnerListener(config);
            //初始化用户点击动作监听，比如新建，删除，转移
            me._initListenUserEvents();
            //缓存
            me.config = config;
            //默认是初始化card
            if (!config.isFold && config.children.length > 0) {
                if (opt.attributes.showMode == 'grid') me._sysInitGrid();
                if (opt.attributes.showMode == 'card') me._sysInitCard();
            }
            me._delay(function() {
                me._triggerOuterEvent('onReferInited', {
                    id: me.getUid()
                });
            })
        },

        getTpl :function(){
            return require('platform/widgets/crm/su/xsySuRefer/widget.tpl');
        },

        getCardTpl : function(){
            return require('platform/widgets/crm/su/xsySuRefer/cardView/widget.tpl');
        },

        getGridTpl : function(){
            return require('platform/widgets/crm/su/xsySuRefer/gridView/widget.tpl');
        },

        _processMultiTypeEntity: function(data, config) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var self = data.self;
            var belongId = self.belongId;
            var entityTypes = self.entityTypes;
            //客户，商机，订单或者自定义对象，如果没有返回业务类型，或者业务类型长度为0,隐藏该卡片
            if ((belongId > 999 || belongId == 1 || belongId == 35 || belongId == 3) && ((entityTypes && entityTypes.length <= 0) || !entityTypes)) {
                var index = config.buttons.indexOf('create');
                config.buttons.splice(index, 1);
            }

        },

        _handleSetMenuSelect: function(button, itemEl, config) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var a = itemEl;
            var li = a.parent();

            var act = a.attr('act');

            var cardDiv = elem.find('.xsy_su_refer_body .xsy_su_refer_card');
            var gridDiv = elem.find('.xsy_su_refer_body .xsy_su_refer_grid');

            if (act == 'grid') {
                cardDiv.hide().removeAttr('current');;
                gridDiv.show().attr('current', 'true');
                var grid_inited = me._sysInitGrid();
                if (!grid_inited) me._updateToLatestData(); //视图切换时，更新最新绑定的数据
                li.siblings().removeClass('active');
                li.addClass('active');
                me._saveAttributes({
                    "showMode": "grid"
                });
                config.opt.attributes.showMode = 'grid';
            } else if (act == 'card') {
                cardDiv.show().attr('current', 'true');
                gridDiv.hide().removeAttr('current');
                var card_inited = me._sysInitCard();
                if (!card_inited) me._updateToLatestData(); //视图切换时，更新最新绑定的数据
                li.siblings().removeClass('active');
                li.addClass('active');
                me._saveAttributes({
                    "showMode": "card"
                });
                config.opt.attributes.showMode = 'card';
            } else if (act == 'toggle') {
                me._toggle();
            }

        },
        _toggle: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var config = me.config;
            var toggle_a = me.header.find('.xsy_su_refer_buttonset [act="toggle"]');
            var suRefer = elem.find('.xsy_su_refer');
            var haveData = opt.haveData;
            if (config.isFold) {
                elem.find('.xsy_su_refer_body').show();
                //a.html('<i></i>收起区域<b></b>').attr('class', 'xsy_su_refer_fewerico');
                toggle_a.find('span').text(rk.i18n('CRM_CORE_COLLAPSE_REFER'));
                toggle_a.closest('li').hide();
                config.isFold = false;
                var visibleChild = elem.find('.xsy_su_refer_body').find('>div:visible');
                var is_inited = false;
                if (visibleChild.hasClass('xsy_su_refer_card')) is_inited = me._sysInitCard();
                if (visibleChild.hasClass('xsy_su_refer_grid')) is_inited = me._sysInitGrid();
                if (is_inited) me._updateToLatestData(); //视图切换时，更新最新绑定的数据
                me._triggerInnerEvent('onFold');
                me._saveAttributes({
                    "expandedFlg": 1
                });
                //有数据，且展开的时候，移除xsy_su_refer_null
                if (haveData) {
                    suRefer.removeClass('xsy_su_refer_null');
                }

            } else {
                elem.find('.xsy_su_refer_body').hide();
                //a.html('<i></i>展开区域<b></b>').attr('class', 'xsy_su_refer_spreadico');
                toggle_a.find('span').text(rk.i18n('CRM_CORE_EXPAND_REFER'));
                toggle_a.closest('li').show();
                config.isFold = true;
                me._triggerInnerEvent('onUnfold');
                me._saveAttributes({
                    "expandedFlg": 0
                });
                //收起的时候，始终加上xsy_su_refer_null
                suRefer.addClass('xsy_su_refer_null');
            }
        },
        _initListenUserEvents: function() {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me._listenInnerEvent('onReferCreateClick', function(info) {
                //console.log('使用之前的新建方法', info)
                //me._create(info);
            });
            me._listenInnerEvent('onReferCellMenuSelect', function(info) {
                var act = info.act;
                //console.log('点击了小菜单', info)
                if ($.isFunction(me['_' + act])) {
                    me['_' + act](info);
                } else {
                    //console.error(me.getType(), '中找不到方法', 'do_'+act)
                }
            });
        },
        _initHeaderEvents: function(config) {
            var me = this;
            var elem = me.element;
            var opt = me.options;


            //初始化右上角菜单按钮
            var expand = elem.find('.xsy_su_refer_buttonset [act="toggle"]');
            var button = elem.find('.xsy_su_refer_set');

            expand.click(function() {
                me._toggle();
            });

            me._delegateMenu({
                buttonSel: '.xsy_su_refer_set',
                menuHtml: rk.templateText(require('platform/widgets/crm/su/xsySuRefer/menus/set_menu.tpl'), config),
                itemSel: 'a[act]',
                position: {
                    my: 'center top',
                    at: 'right+19 bottom'
                },
                onOpen: function(button, menuSel, menuPos) {
                    var a = $(menuSel).find('a[act="toggle"]');
                    var toggleLi = a.parent();
                    if (me.config.isFold) {
                        a.html('<i></i>' + rk.i18n('CRM_CORE_EXPAND_REFER') + '<b></b>').attr('class', 'xsy_su_refer_spreadico');
                    } else {
                        a.html('<i></i>' + rk.i18n('CRM_CORE_COLLAPSE_REFER') + '<b></b>').attr('class', 'xsy_su_refer_fewerico');
                    }
                },
                onSelect: function(e, button, itemEl) {
                    me._handleSetMenuSelect(button, itemEl, config);
                }
            });

            if ($.isArray(config.entityTypes) && config.entityTypes.length > 1) {
                //初始化新建【+】按钮菜单
                var menuHtml = rk.templateText(require('platform/widgets/crm/su/xsySuRefer/menus/create_menu.tpl'), config);
                me._delegateMenu({
                    buttonSel: '.xsy_su_refer_create',
                    menuHtml: menuHtml,
                    itemSel: 'li',
                    position: {
                        my: 'center top',
                        at: 'right+10 bottom'
                    },
                    onOpen: function(button, menuSel, menuPos) {},
                    onSelect: function(e, button, itemEl) {
                        var btn = itemEl;
                        var id = btn.data('id');
                        var entitytype = me._getEntityType(id);
                        me._triggerInnerEvent('onReferCreateClick', entitytype);
                    }
                });
            } else {
                var entitytype = $.isArray(config.entityTypes[0]) ? config.entityTypes[0] : {};
                elem.find('.xsy_su_refer_create').data({
                    id: entitytype.id,
                    tenantId: entitytype.tenantId,
                    name: entitytype.name,
                    entityId: entitytype.entityId,
                }).click(function(e) {
                    var btn = $(e.target);
                    var id = btn.data('id');
                    var entitytype = me._getEntityType(id);
                    me._triggerInnerEvent('onReferCreateClick', entitytype);
                });
            }
        },
        _initBodyEvents: function(config) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var uuid = elem.attr('id');

            //if(!config.showCard) return;
            if (!config.showEntityMenu) return;

            var DropDownMenu_Sel = '.xsy_su_refer_card_toolbar_tip';
            var DropDownBtn_Sel = config.cardConfig.menuButton ? config.cardConfig.menuButton : '.xsy_su_refer_card_toolbar';
            var DropDownBtn_key = DropDownBtn_Sel.replace(/\./ig, '');

            var menuTpl = require('platform/widgets/crm/su/xsySuRefer/menus/card_tipmenu.tpl');
            var menuHtml = rk.templateText(menuTpl, {
                items: config.cardConfig.menuItems
            });
            rk.delegateMenu({
                container: elem,
                buttonSel: DropDownBtn_Sel,
                menuHtml: menuHtml,
                itemSel: 'a[act]',
                position: {
                    my: 'center top',
                    at: 'right-12 bottom+10'
                },
                beforeOpen: function(button, menuSel) {
                    var row = button.closest('[data-rid]');
                    var rowId = row.data('rid'); //菜单所在的内容区域
                    var entityData = me._getEntityData(rowId);
                    if (!entityData) entityData = {};
                    var permissions = rk.dataMgr.mergePermission(opt.userPermission, entityData.permissions);
                    entityData.permissions = permissions;
                    if (typeof permissions != 'undefined') {
                        var menu = $(menuSel).find('ul');
                        /*if(permissions['delete'] === false) menu.find('a[act="remove"]').closest('li').remove(); 
                        if(permissions['transfer'] === false) menu.find('a[act="transfer"]').closest('li').remove(); 
                        if(permissions['update'] === false) menu.find('a[act="edit"]').closest('li').remove(); */

                        /**
                        这里有权限往上面append,不能没权限去remove
                        */
                        menu.html("");
                        var menuHtml = ''
                        // if (permissions['update'] === true) menuHtml += '<li><a act="edit" href="javascript:">' + rk.i18n('CRM_CORE_EDIT') + '</a></li>';
                       /* if (permissions['delete'] === true) menuHtml += '<li><a act="delete" href="javascript:">' + rk.i18n('CRM_CORE_DELETE') + '</a></li>';
                        if (permissions['remove'] === true) menuHtml += '<li><a act="remove" href="javascript:">' + rk.i18n('CRM_CORE_REMOVE') + '</a></li>';
                        if (permissions['transfer'] === true) menuHtml += '<li><a act="transfer" href="javascript:">' + rk.i18n('CRM_CORE_TRANSFER') + '</a></li>';*/

                        var menuItems = rk.dataMgr.getOpMenuItems(permissions);

                        menuItems.forEach(function(item, i){
                            menuHtml += '<li><a act="' + item.act + '" href="javascript:">' + item.label + '</a></li>'
                        })

                        menu.html(menuHtml);

                        if (menu.find('li').size() == 0) return false; //一项也没有，就不弹出了
                    } else {
                        return false; //不显示菜单
                    }
                    return true; //显示菜单
                },
                afterOpen: function(button, menuSel, menuPos) {
                    if (me._getCurrentViewtype() == 'grid') {
                        $(menuSel).position({
                            of: $(button),
                            my: 'center top',
                            at: 'left+8 bottom+10'
                        });
                    }
                    button.find("i.xsy_su_refer_arrow").addClass('xsyvisible');
                },
                onSelect: function(e, button, itemEl) {
                    var a = itemEl;
                    var act = a.attr('act')
                    var row = button.closest('[data-rid]');
                    var rowId = row.data('rid'); //菜单所在的内容区域
                    var entityData = me._getEntityData(rowId);
                    if (!entityData) entityData = {};
                    entityData.act = act;
                    entityData.config = config;
                    button.trigger('onReferCellMenuSelect', entityData);
                    button.find("i.xsy_su_refer_arrow").removeClass('xsyvisible');
                }
            });
        },
        _initInnerListener: function() {
            var me = this;
            var elem = me.element;
            me._listenInnerEvent('onReferWidthData', function(info) {
                elem.find('.xsy_su_refer:first').removeClass('xsy_su_refer_null');
                me._triggerOuterEvent('onReferWidthData', info); //向外发送
            });
            me._listenInnerEvent('onReferWidthoutData', function(info) {
                elem.find('.xsy_su_refer:first').addClass('xsy_su_refer_null');
                me._triggerOuterEvent('onReferWidthoutData'); //向外发送
            });
        },
        _sysInitCard: function() {
            var me = this;
            var card = me._getCard();
            //切换的时候都进行数据刷新
            //if(card.data('inited'))return true;
            var doBinding = me._initCardView(card, me.currentServerData);
            card.data('inited', true); //不要在initCard中打标记，因为会被子类重写 
            if (doBinding) me.bindData(me.currentServerData);
            me._triggerInnerEvent('onReferCardInited');
            return false;
        },
        _sysInitGrid: function() {
            var me = this;
            var grid = me._getGrid();
            //切换的时候进行数据刷新
            //if(grid.data('inited'))return true;
            var doBinding = me._initGridView(grid, me.currentServerData);
            grid.data('inited', true); //不要在initCard中打标记，因为会被子类重写 
            if (doBinding) me.bindData(me.currentServerData);
            me._triggerInnerEvent('onReferGridInited');
            return false;
        },
        _initCardView: function(cardElem, data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var config = me.config;
            if (cardElem.size() == 0) return;
            var cardConfig = {};
            for (var i = 0, len = config.children.length; i < len; i++)
                if (config.children[i].type == 'card') cardConfig = config.children[i];
            cardElem.xsyReferCardView($.extend(true, {
                belongId: me._getBelongId(),
                ownerId: me.getUid(),
                ownerData: data,
                ownerConfig: me.config,
                cardConfig: cardConfig,
                maxRows: (opt.attributes && opt.attributes.maxCardRowCount) ? opt.attributes.maxCardRowCount : 3,
                maxCols: opt.attributes.maxCardColCount,
                tpl : me.getCardTpl()
            }, opt));
            me.cardElem = cardElem;
            return true; //true代表着允许接下来执行bindData方法
        },
        _initGridView: function(gridElem, data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var config = me.config;
            if (gridElem.size() == 0) return;
            var gridConfig = {};
            for (var i = 0, len = config.children.length; i < len; i++)
                if (config.children[i].type == 'grid') gridConfig = config.children[i];
            gridElem.xsyReferGridView($.extend(true, {
                belongId: me._getBelongId(),
                ownerId: me.getUid(),
                ownerData: data,
                ownerConfig: me.config,
                gridConfig: gridConfig,
                maxRows: (opt.attributes && opt.attributes.maxGridRowCount) ? opt.attributes.maxGridRowCount : 6,
                maxCols: opt.attributes.maxGridColCount,
                tpl : me.getGridTpl()
            }, opt));
            me.gridElem = gridElem;
            return true; //true代表着允许接下来执行bindData方法
        },
        changeHeader: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var referTitle = elem.find('.xsy_su_refer_title');
            var referTitleLink = referTitle.find('a');
            if (data.dataCount || data.dataCount == 0) {
                if (data.dataCount == 0) {
                    elem.find(".xsy_su_refer_more").hide();
                    referTitleLink.attr('href', 'javascript:void(0)');
                } else {
                    elem.find(".xsy_su_refer_more").show();
                    referTitleLink.attr('href', referTitle.attr('url'));
                }
                me._getReferHeaderNum().html(data.dataCount);
            }
        },
        bindData: function(data) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            me.changeHeader(data);

            if (!data || !data.entityData || data.entityData.length == 0) {
                me._getGrid().empty().hide();
                me._getCard().empty().hide();
                //elem.find('.xsy_su_refer:first').addClass('xsy_su_refer_null');
                me._triggerInnerEvent('onReferWidthoutData');
                return;
            } else {
                //elem.find('.xsy_su_refer:first').removeClass('xsy_su_refer_null');
                me._triggerInnerEvent('onReferWidthData', {
                    dataCount: data.dataCount ? data.dataCount : data.entityData.length
                });
                me._getCurrentViewElem().show();
            }
            if (data && data.self) data = data.self; //防止传入的是result
            if ($.isArray(data.entityData)) {
                for (var i = 0, len = data.entityData.length; i < len; i++) {
                    var entityData = data.entityData[i];
                    //随机生成一个id，便于查找
                    if (typeof entityData.id == 'undefined') entityData.id = 'row_' + (Math.round(Math.random() * 100000) + '').replace(/\./g, '');
                    //if(typeof entityData.permissions == 'undefined') entityData.permissions = 'all'
                    var permissions = rk.dataMgr.mergePermission(opt.userPermission, entityData.permissions);
                    entityData.permissions = permissions;
                    //if(entityData.entityType && !entityData.belongId)entityData.belongId = entityData.entityType.belongId;
                    if (data.belongId) entityData.belongId = data.belongId;
                    data.entityData[i] = entityData;
                }
            }
            var viewType = me._getCurrentViewtype();
            if (viewType == 'card') {
                me._bindCardData(data);
                me._getGrid().attr('data_out_of_date', 'true');
            }
            if (viewType == 'grid') {
                me._bindGridData(data);
                me._getCard().attr('data_out_of_date', 'true');
            }

            me.currentServerData = data;
            me.data_bound = true; //已绑定数据
        },
        _bindGridData: function(data) {
            var me = this;
            if (me._getGrid().size() == 0 || !me._getGrid().data('inited')) return;
            if (me._getGrid().attr('wtype') != 'xsyReferGridView') return;
            me._getGrid().xsyReferGridView('bindData', data);
            me._getGrid().removeAttr('data_out_of_date');
        },
        _bindCardData: function(data) {
            var me = this;
            if (me._getCard().size() == 0 || !me._getCard().data('inited')) return;
            if (me._getCard().attr('wtype') != 'xsyReferCardView') return;
            me._getCard().xsyReferCardView('bindData', data);
            me._getCard().removeAttr('data_out_of_date');
        },
        _updateToLatestData: function() {
            return; //似乎用不到了
            var me = this;
            me.body.find('>div:visible').each(function(i, el) {
                if ($(el).hasClass('xsy_su_refer_card')) me._bindCardData(me.currentServerData);
                if ($(el).hasClass('xsy_su_refer_grid')) me._bindGridData(me.currentServerData);
            });
        },
        _getCardTpl: function() {
            return require('platform/widgets/crm/su/xsySuRefer/cardView/widget.tpl')
        },
        _getEntityData: function(id) {
            var me = this;
            if (me.currentServerData && $.isArray(me.currentServerData.entityData)) {
                var datalist = me.currentServerData.entityData;
                for (var i = 0, len = datalist.length; i < len; i++) {
                    if (datalist[i].id == id) return datalist[i];
                }
            }
        },
        _getEntityType: function(id) {
            var me = this;
            if (me.currentServerData && $.isArray(me.currentServerData.entityTypes)) {
                var datalist = me.currentServerData.entityTypes;
                for (var i = 0, len = datalist.length; i < len; i++) {
                    if (datalist[i].value == id) return datalist[i];
                }
            }
        },
        //////////////////////////
        do_edit: function(celldata, callback) {
            var me = this;
            var elem = me.element;
            var opt = me.options;

            var data = {};
            data.business = opt.business;
            data.businessname = celldata.config.title;

            var postdata = {};
            postdata[opt.business + 'Id'] = celldata.id;
            data.postdata = JSON.stringify(postdata);
            data.belongId = opt.business === "customize" ? celldata.belongId : undefined;
            data.relationId = celldata.config.detailId;
            data.relationBelongId = me._getBelongId();
            $('body').editBusiness('option', 'onSuccess', callback);
            $('body').editBusiness('newEdit', data);
        },

        do_cascadeDelete : function(celldata, businessData, callback){
            var me = this;
            var elem = me.element;
            var opt = me.options;
        
            $.postJson(businessData.validateUrl, businessData.postJson).done(function(json){
                var html = businessData.confirmTip(json);

                $.confirm(html, function(){
                    $.postJson(businessData.url, businessData.postJson).done(function(json){
                        if (json.status == 0) {
                            $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                            me._reload();
                            me._triggerOuterEvent('referDataUpdated');
                        } else if (json.status == 300001) {
                            $.msg(rk.i18n('CRM_CORE_NO_PERMISSION') + rk.i18n('CRM_CORE_DELETE'));
                        } else {
                            if (json.data.errorObjects) {
                                var msg = $.map(json.data.errorObjects, function(o) {
                                    return [rk.i18n('CRM_CORE_DELETE') + '【', o.name, '】' + rk.i18n('CRM_CORE_FAILED') + '：', o.message].join('');
                                }).join('<br/>');
                            } else {
                                $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_FAILED'));
                            }
                        }
                    }).fail(function(def, code, message) {
                        def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                    });
                })
            }).fail(function(def, code, message) {
                def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
            });
        },

        do_delete: function(celldata, callback) {
            var me = this;
            var elem = me.element;
            var opt = me.options;
            var html_substr = celldata.config.title + '【' + celldata.name + '】';
            var html = rk.i18n('ACCOUNT_DELETE_ARRAY_STRING_1', html_substr);

            var params = {};
            params[opt.business + 'Ids'] = celldata.id;

            var isCustomize = "";
            if (opt.business === 'customize') {
                isCustomize = "?belongId=" + celldata.belongId;
            }

            $.confirm(html, function() {
                $.postJson('/json/crm_' + opt.business + '/delete.action' + isCustomize, params).done(function(json) {
                    if (json.status == 0) {
                        $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                        callback();
                    } else if (json.status == 300001) {
                        $.msg(rk.i18n('CRM_CORE_NO_PERMISSION') + rk.i18n('CRM_CORE_DELETE'));
                    } else {
                        if (json.data.errorObjects) {
                            var msg = $.map(json.data.errorObjects, function(o) {
                                return [rk.i18n('CRM_CORE_DELETE') + '【', o.name, '】' + rk.i18n('CRM_CORE_FAILED') + '：', o.message].join('');
                            }).join('<br/>');
                        } else {
                            $.msg(rk.i18n('CRM_CORE_DELETE') + rk.i18n('CRM_CORE_FAILED'));
                        }
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });
        },

        do_remove : function(celldata, callback){
            var me = this,
                opt = me.options;

            var postData = {
                opportunityId : me._getDetailId(),
                entityIds : celldata.relationId
            }

            var businessToUrl = {
                'partner' : 'account',
                'competitor' : 'account',
            }

            $.confirm(rk.i18n('CRM_CORE_REMOVE_CONFIRM_1'), function() {
                $.postJson('/json/crm_opportunity/remove-' + (businessToUrl[opt.business] ? businessToUrl[opt.business] : opt.business)  + 's.action', postData).done(function(json) {
                    if (json.status == 0) {
                        $.msg(rk.i18n('CRM_CORE_REMOVE') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                        callback();
                    } else {
                        $.msg(rk.i18n('CRM_CORE_REMOVE') + rk.i18n('CRM_CORE_FAILED'));
                    }
                }).fail(function(def, code, message) {
                    def.status != 0 && $.msg(rk.i18n('REQUEST_ERROR'));
                });
            });
            return false;

        },

        do_transfer: function(celldata, callback, optionsParams) {
            var me = this,
                opt = me.options;

            var params = {};
            params[opt.business + 'Ids'] = celldata.id;
            if (opt.business === 'customize') {
                params.belongId = celldata.belongId;
            }
            $.postJson('/json/crm_' + opt.business + '/validate-transfer.action', params).done(function(json) {
                if (json.status == 0) {
                    var html_substr = celldata.config.title + '【' + celldata.name + '】';
                    var pre = '<div class="pop_up_02"><div class="pop_up_content"><div class="add_new_list clear"><div class="field clear"><div class="field_name"></div><div class="field_content">';
                    var end = '</div></div><div class="field clear"><div class="field_name">' + rk.i18n('CRM_CORE_NEW') + rk.i18n('CRM_CORE_IN_CHARGE') + '：</div><div class="field_content"><input type="text" class="text" field="transferUser" placeholder="' + rk.i18n('CRM_CORE_INPUT_SELECT') + rk.i18n('CRM_CORE_IN_CHARGE') + '"></div></div></div></div><div class="pop_up_bottom"><div class="pop_up_button"><a title="" href="javascript:;" class="green_button" act="save">' + rk.i18n('CRM_CORE_CONFIRM') + '</a></div></div></div>';

                    if (optionsParams && optionsParams.endHtml) {
                        end = optionsParams.endHtml;
                    }

                    var html = rk.i18n('ACCOUNT_TRANSFER_ARRAY_STRING', pre, html_substr, end);

                    me.dialog = $(html);
                    var inputElem = me.dialog.find('input[field=transferUser]');

                    if (optionsParams && optionsParams.accountHtml) {
                        optionsParams.accountHtml(me.dialog, json.data);
                    }

                    me.dialog.popup({
                        width: 520,
                        title: rk.i18n('CRM_CORE_TRANSFER') + celldata.config.title,
                        actions: {
                            save: function(evt, dialog) {
                                var transferUserId = inputElem.attr('ownerId');
                                if (transferUserId) {
                                    params.target = transferUserId;
                                    if (optionsParams && optionsParams.saveActionParams) {
                                        params = optionsParams.saveActionParams(params, me.dialog);
                                    }
                                    $.postJson('/json/crm_' + opt.business + '/transfer.action', params).done(function(json) {
                                        $.msg(json.statusText, json.status == 0);
                                        if (json.status == 0) {
                                            //need to some refesh things
                                            $.msg(rk.i18n('CRM_CORE_TRANSFER') + rk.i18n('CRM_CORE_SUCCESS'), 1);
                                            callback();
                                            dialog.close();
                                        } else {
                                            if (json.data) {
                                                var msg = $.map(JSON.parse(json.data), function(o) {
                                                    return [rk.i18n('CRM_CORE_TRANSFER') + '【', o.name, '】' + rk.i18n('CRM_CORE_FAILED') + '：', o.message].join('');
                                                }).join('<br/>');
                                            } else {
                                                $.msg(rk.i18n('CRM_CORE_TRANSFER') + rk.i18n('CRM_CORE_FAILED'));
                                            }
                                        }
                                    });
                                } else {
                                    $.msg(rk.i18n('ACCOUNT_SELECTED_TRANSFER_TO'), false);
                                }
                            }
                        },
                        create: function() {
                            inputElem.autocomplete({
                                minLength: 0,
                                source: function(request, response) {
                                    var key = $.trim(request.term);
                                    $.postJson("/json/crm_search/all-users.action", {
                                        pageNo: 1,
                                        key: key
                                    }).done(function(data) {
                                        var id;
                                        if (data.length > 0) {
                                            $.each(data, function(i, d) {
                                                if (d.value == key) {
                                                    id = d.id;
                                                }
                                            });
                                        }
                                        id ? inputElem.attr('ownerId', id) : inputElem.removeAttr('ownerId');
                                        response(data);
                                    });
                                },
                                select: function(event, ui) {
                                    var id = ui.item.id;
                                    inputElem.attr('ownerId', id);
                                }
                            });
                        }
                    });
                } else if (json.status == 300001) {
                    $.msg(rk.i18n('CRM_CORE_NO_PERMISSION') + rk.i18n('CRM_CORE_TRANSFER'));
                } else if (json.status == 310005) {
                    $.msg(rk.i18n('CAMPAIGN_LEAD_TRANSFER_CONDITION_FAILED', json.data, SESSION.keywords.opportunity));
                }
            }).fail(function(def, code, message) {
                $.msg(rk.i18n('REQUEST_ERROR'));
            });
        },
        _edit: function(info) {
            var me = this;
            me.do_edit(info, function() {
                me._reload();
                me._triggerOuterEvent('referDataUpdated');
            });
        },
        _delete: function(info) {
            var me = this;
            me.do_delete(info, function() {
                me._reload();
                me._triggerOuterEvent('referDataUpdated');
            });
        },

        //delete删除， remove移除
        _remove: function(info){
            var me = this;
            me.do_remove(info, function(){
                me._reload();
                me._triggerOuterEvent('referDataUpdated');
            })
        },

        _transfer: function(info) {
            var me = this;
            me.do_transfer(info, function() {
                me._reload();
                me._triggerOuterEvent('referDataUpdated');
            });
        }
    });
});
